<?php

namespace app\model;

use support\Log;
use yzh52521\EasyHttp\Http;

/**
 *微信通讯录模型
 */
class Contact extends BaseModel
{
    /**
     * 从微信数据库根据昵称查找对应的wxid
     * @param $nickname
     * @return string
     */
    public function getUserNameByNickname($nickname): string
    {
        $username = '';
        try {
            $url = Config::getApiBaseUrl() . '/api/execsql';
            $sql = "SELECT `UserName` FROM `contact` WHERE  `NickName` = '{$nickname}' LIMIT 1";
            $data = [
                'dbName' => 'MicroMsg.db',
                'sql' => $sql,
            ];
            $response = Http::asJson()->post($url, $data);
            $result = $response->array();
            if (isset($result['code']) && $result['code'] == 200 && !empty($result['data'])) {
                $username = $result['data'][0]['UserName'];
            }
            return $username;
        } catch (\Exception$e) {
            Log::error('根据昵称查找对应的wxid失败：' . $e->getMessage());
        }
    }

    /**
     * 从数据库中通过WXID查找昵称
     * @param $wxid
     * @return string
     */
    public function getNickNameByWxid($wxid): string
    {
        $nickname = '';
        try {
            $url = Config::getApiBaseUrl() . '/api/dbaccountbywxid';
            $data = [
                'wxid' => $wxid,
            ];
            $response = Http::asJson()->post($url, $data);
            $result = $response->array();
            if (isset($result['code']) && $result['code'] == 200 && !empty($result['data'])) {
                $nickname = $result['data']['NickName'];
            }
        } catch (\Exception $e) {
            Log::error('获取昵称失败：' . $e->getMessage());
        }
        return $nickname;
    }

    /**
     * 获取数据库中的所有联系人信息
     * @return array
     */
    public function dbcontacts(): array
    {
        try {
            $response = Http::get(Config::getApiBaseUrl() . '/api/dbcontacts');
            $contact_res = $response->array();
            return $contact_res['data']['contacts'];
        } catch (\Exception $e) {
            return [
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }

    /**
     * 根据昵称关键字查找对应的wxid
     * @param $keyword
     * @return string
     */
    public function getUserNameByNickNameKeyword($keyword): string
    {
        try {
            $keyword = trim($keyword);
            $url = Config::getApiBaseUrl() . '/api/execsql';
            $sql = "SELECT * FROM `contact` WHERE  `NickName` LIKE '%{$keyword}%'";
            $data = [
                'dbName' => 'MicroMsg.db',
                'sql' => $sql,
            ];
            $response = Http::asJson()->post($url, $data);
            $result = $response->array();
            $str = '';
            foreach ($result['data'] as $v) {
                //把结果按照“昵称=>微信号”格式拼接成字符串，每行一个
                $str .= $v['NickName'] . '=>' . $v['UserName'] . PHP_EOL;
            }
            //删除最后一个换行符
            $return_str = rtrim($str, PHP_EOL);
            if (empty($return_str)) {
                $return_str = '没有找到匹配的结果';
            } else {
                $return_str = '找到以下结果:' . PHP_EOL . $return_str;
            }
            return $return_str;
        } catch (\Exception $exception) {
            Log::error('根据关键字查找对应的wxid报错了：' . $exception->getMessage());
            return '查找失败';
        }
    }
}
